// sortObject - Sorts an object returning an array.
function sortObject(b){var a=[];for(i in b)a.push(b[i]);for(i in a.sort())for(j in b)if(b[j]==a[i]){a[i]=[j,a[i]];delete b[j]}return a}

function endOfRound(snakes){
	for( s in snakes ){
		if( SCORES[s] >= NUM_SNAKES * 10 ) return endOfGame();
	}
	runAuchtung();
}

function endOfGame(){
	$("#score").hide().html('');
	$('#canvas_auchtung').hide();
	$('#finalScore ul').html('');
	$('#finalScore').show();
	
	SCORES = sortObject(SCORES).reverse();
	
	for( s in SCORES ){
		var score = SCORES[s][1];
		var p_number = parseInt(SCORES[s][0]);
		var c = PLAYER_COLORS[ p_number ];
		var rgb = "rgb(" + c[0] + "," + c[1] + "," + c[2] + ")";
		$('#finalScore ul').append(
			$('<li/>', {
				text: 'Player ' + (p_number+1) + ' - ' + score,
				css: {color: rgb}
			})
		);
	}
	
	SCORES = {};
	
	$('#settings_btn').click(function(){
		$('#finalScore').hide();
		$('#config').show();
	});
	$('#restart_btn').click(function(){
		$('#finalScore').hide();
		runAuchtung();
	});
	
}

function updateGlobalScore(snakes){
	for( s in snakes ){
		if( !SCORES[s] ) SCORES[s] = 0;
		SCORES[s] += snakes[s].score;
		snakes[s].score = 0;
		$("#playerScore" + s).find('.scoreNum').text(SCORES[s]);
	}
}

function runAuchtung(){
	if( $(".playerControlls").length < 2 ) return;
	
	$("#config").hide();
	// Reset global vars
	CANVAS_HEIGHT = window.innerHeight;
	CANVAS_WIDTH = window.innerWidth - 150;
	KEY_DOWN = {};
	SNAKES = {};
	NUM_SNAKES = 0;
	
	var snakeNum = -1;
	// Set up the SNAKES
	$(".playerControlls").each(function(){
		snakeNum ++;
		if( !$(this).data('right') || ! $(this).data('left') ) return;
		NUM_SNAKES ++;
		SNAKES[ snakeNum ] = {
			color: PLAYER_COLORS[snakeNum],
			leftKey: $(this).data('left'),
			rightKey: $(this).data('right')
		};
		
		var c = PLAYER_COLORS[ snakeNum ];
		var rgb = "rgb(" + c[0] + "," + c[1] + "," + c[2] + ")";
		
		// Set up scores div if there isn't one already
		if( $("#playerScore" + snakeNum).length != 0 ) return;
		$("#score").append(
			$('<div />', {
				'class':"playerScore",
				id: "playerScore" + snakeNum,
				html: 'Player ' + (snakeNum+1) +': <span class="scoreNum">0</span>',
				css: {color: rgb}
		}));
	});	
	
	
	script = document.getElementById('script_auchtung');
	canvas = document.getElementById('canvas_auchtung');
	
	// Only show countdown first run each game
	if( $('#canvas_auchtung').is(':hidden') ){
		startCountDown(canvas, script.text)
	} else {
		setTimeout( function(){Processing(canvas, script.text);}, 1000 );
	}
}

function startCountDown( canvas, script ){
	$("#countDown").css({display: 'table', opacity: 0}).find('.time').text('3');
	$("#countDown").animate({opacity: 1}, 700, function(){
		$(this).css({opacity: 0});
		$(this).find('.time').text('2');
		$(this).animate({opacity: 1}, 700, function(){
			$(this).css({opacity: 0});
			$(this).find('.time').text('1');
			$(this).animate({opacity: 1}, 700, function(){
				$(this).css({opacity: 0});
				$(this).find('.time').text('GO!');
				$(this).animate({opacity: 1}, 700, function(){
					$(this).css({display: 'none'});
					$("#score").show();
					$('#canvas_auchtung').height(CANVAS_HEIGHT).width(CANVAS_WIDTH).show();
					Processing(canvas, script);
				});
			});
		});
	});
}